package com.module.circle.ui.circleMembersList

import android.graphics.Typeface
import android.view.View
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.common.app.base.AppActivity
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.utls.HeadTitleUtils
import com.common.base.app.extras.getShowMsg
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.listener.AlertDialogConfirmBtnListener
import com.common.base.utils.SpanUtils
import com.common.base.utils.StatusBarUtils
import com.common.base.widget.animator.CustomAnimation1
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.circle.R
import com.module.circle.databinding.CircleActivityMembersListBinding
import com.module.circle.ui.dialog.MemberInfoDialog
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/07/30
 * <p>
 * 描述：圈子成员列表页面
 * <p>
 * 修订历史：
 */
class MembersListActivity : AppActivity<CircleActivityMembersListBinding, MembersListViewModel>(),
    View.OnClickListener, MemberInfoDialog.OnMemberInfoDialogListener {

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var mId: Int = 0

    @Autowired(name = KeyBundle.EXPAND_DATA)
    @JvmField
    var isLeader: Boolean = false

    override fun getViewModel() = MembersListViewModel::class.java

    override fun getViewContentBinding() = CircleActivityMembersListBinding.inflate(layoutInflater)

    override fun getPageTitle(): String = ""
    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    private val classicsFooter by lazy { ClassicsFooter(this) }

    private val mAdapter by lazy { MembersListItemAdapter(isLeader) }

    private val headTitleUtils by lazy { HeadTitleUtils(this) }

    private val memberInfoDialog by lazy { MemberInfoDialog(this) }

    override fun initViews() {
        super.initViews()

        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        headTitleUtils.setTitle(getString(R.string.common_member_hint))
        headTitleUtils.setLineStyle(10)


        //上下拉刷新
        getRefreshFooter()?.let { mViewContentBinding.pdView.setRefreshFooter(it) }
        mViewContentBinding.pdView.setRefreshHeader(
            ClassicsHeader(this).setAccentColor(
                ContextCompat.getColor(this, R.color.text_content_week)
            )
        )
        classicsFooter.setAccentColor(
            ContextCompat.getColor(
                this,
                R.color.color_999999
            )
        )
        mViewContentBinding.pdView.setRefreshFooter(classicsFooter)

        mAdapter.apply {
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = true
//            isAnimationFirstOnly = false
            mViewContentBinding.hrv.adapter = this
        }
    }

    override fun initEvents() {
        super.initEvents()

//        mViewContentBinding.tvTitleRight.setOnClickListener(onClick = this)
        mViewContentBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                lazyInitData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewContentBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
                mViewContentBinding.pdView.finishLoadMoreWithNoMoreData()
            }
        })

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.totalRoot->{
                    memberInfoDialog.isShowing.no {
                        memberInfoDialog.show(mAdapter.data[position])
                    }
                }
                R.id.tvDelBtn->{
                    val titleTemp = getString(R.string.circle_confirm_removal_members_hint)
                    val msgTemp = getString(
                        R.string.circle_splicing_members_name_hint,
                        mAdapter.data[position].nickname
                    )
                    showAlertDialogTwoBtn(
                        getString(R.string.cancel_btn_zh),
                        getString(R.string.ok_btn_zh),
                        titleTemp,
                        message = "",
                        message2 = msgTemp,
                        true,
                        object : AlertDialogConfirmBtnListener {
                            override fun onCancelBtnClick() {
                            }

                            override fun onConfirmBtnClick() {
                                requestDelCirclesMembers(mAdapter.data[position].user_id)
                            }
                        }).run {
                        this?.getTitleView()?.apply {
                            SpanUtils.create()
                                .addSection(titleTemp)
                                .setAbsSize(titleTemp, 16)
                                .setStyle(titleTemp, Typeface.BOLD)
                                .showIn(this)
                        }

                        this?.getMsg2View()?.apply {
                            SpanUtils.create()
                                .addSection(msgTemp)
                                .setAbsSize(msgTemp, 14)
                                .showIn(this)
                        }
                    }
                }
            }
        }

        memberInfoDialog.setListener(this)
    }

    override fun lazyInitData() {
        super.lazyInitData()
        requestCirclesMembersList()
    }

    override fun onClick(v: View?) {
        when (v) {
//            mViewContentBinding.tvTitleRight -> LaunchHelper.launchWebActivity(ApiConstant.SECKILL_RULE)
        }
    }

    private fun finishPdView() {
        mViewContentBinding.pdView.finishRefresh()
        mViewContentBinding.pdView.finishLoadMore()
    }

    private fun requestCirclesMembersList() {
        if (mId <= 0){
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.getCirclesMembersList(mId){
            finishPdView()
        }.observe(this) {
            finishPdView()
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.Data?.let{ dataIt->
                    mAdapter.setList(dataIt.members)
                    headTitleUtils.setTitle("${getString(R.string.common_member_hint)}(${mAdapter.data.size}${getString(R.string.circle_ren_splicing_hint)})")
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    private fun requestDelCirclesMembers(memberId:Int) {
        if (mId<=0){
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.requestDelCirclesMembers(mId,memberId){
            showToast(it.getShowMsg())
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                // 删除指定user_id的数据项
                val iterator = mAdapter.data.iterator()
                while (iterator.hasNext()) {
                    val item = iterator.next()
                    if (item.user_id == memberId) {
                        iterator.remove()
                        break
                    }
                }
                // 刷新UI
                mAdapter.notifyDataSetChanged()
                headTitleUtils.setTitle("${getString(R.string.common_member_hint)}(${mAdapter.data.size}${getString(R.string.circle_ren_splicing_hint)})")
                LiveEventBus.get(KeyEvents.KEY_REFRESH_CIRCLE_DETAILS_EVENT).post(this)
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    override fun onMemberInfoChange(mId: Int, isLike: Boolean,likeCount:Long) {
        mAdapter.data.forEachIndexed { index, data ->
            (data.user_id == mId).yes {
                data.is_liked = isLike
                data.like_count = likeCount
//                mAdapter.notifyItemChanged(index)
                return@forEachIndexed
            }
        }
    }
}